//
//  TKIMChartViewController.m
//  TKIM
//
//  Created by liupm on 15/7/27.
//  Copyright (c) 2015年 liupm. All rights reserved.
//

#import "TKIMChatViewController.h"
#import "TKIMChatView.h"
#import "TKIMEmotionView.h"
#import "TKIMLayerUtils.h"
#import "TKIMLocationViewController.h"
//#import "TKIMOfficalDetailViewController.h"
#import "EBMWebViewViewController.h"
#import "TKIMHttpRequestHelper.h"
#import "TKIMRequestService.h"
#import "IQKeyboardManager.h"


@interface TKIMChatViewController ()<TKIMMessageDelegate,TKIMManagerDelegate>
@property(nonatomic,strong) TKIMChatView *chatView;
@property (nonatomic,strong)NSMutableArray * menusArray;
@property (nonatomic,strong) NSTimer * timer;
@property (nonatomic,strong) UILabel* reddot;
@property(nonatomic,strong) NSMutableArray *msgArray;
@property(nonatomic,strong) TKIMMessage *msgInit;
@end

@implementation TKIMChatViewController

#pragma mark 系统方法

-(void)loadView
{
    [super loadView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.msgArray=[[NSMutableArray alloc] init];
    //查询历史用户
    //    TKIMUser *hisUser = [[TKIMManager shareInstance] queryAHisUserByUserId:_user.userID];
    //    if (hisUser)
    //    {
    //        _user = hisUser;
    //    }
    
    NSString *userMaxDay = [TKIMSDKConfig shareInstance].tkUserMaxDay;
    NSInteger *maxDay = [userMaxDay integerValue];
    
    [[TKIMManager shareInstance]asyncDeleteUserHisMessageByUserId:_user.userID maxDay:maxDay];
    
    if (_channel == 1) {
        [self rightPhoneBtn];
    }
    [self backStyle];
    
    CGFloat bar_height  = NAVIGATION_BAR_HEIGHT;
    CGFloat home_height = HOME_INDICATOR_HEIGHT;
    NSLog(@"bar_height = %f, home_height =%f",bar_height,home_height);
    
    //聊天界面
    _chatView = [[TKIMChatView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-NAVIGATION_BAR_HEIGHT -HOME_INDICATOR_HEIGHT) channel:_channel type:TKIMToolBarNormalType];
    _chatView.toolBar.isNeedVoice = NO;
    __weak __typeof(self) weakSelf=self;
    
    _chatView.kefuMenu.block=^(id hander,id data){
        __strong __typeof(self)strongSelf =weakSelf;
        [strongSelf.navigationController popViewControllerAnimated:YES];
    };
    
    _chatView.delegate = self;
    [self.view addSubview:_chatView];
    
    [[TKIMManager shareInstance] asyncQueryUserHisMessageByUserId:_user.userID callBack:^(NSMutableArray *array)
     {
         [weakSelf.msgArray insertObjects:array atIndexes:[[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, array.count)]];
         [_chatView reloadList:weakSelf.msgArray isNeedTime:!self.user.isNeedMangerBtn];
     }];
}

-(void)backStyle
{
    UIButton* backBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
    [backBtn addSubview:self.reddot];
    NSInteger total = [[TKIMDBManager shareInstance] queryConverseTotal];
    NSString * str = @"消息";
    if (total>0) {
        str = [NSString stringWithFormat:@"消息(%ld%@)",total>99?99:total ,total>99?@"+":@""];
    }
    [backBtn  setTitle:str forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [backBtn setImage:TKIMGetImage(@"btn_back@2x") forState:UIControlStateNormal];
    //    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 0);
    //    backBtn.titleEdgeInsets = UIEdgeInsetsMake(5, -8, 5, 5);
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}


-(void)rightPhoneBtn{
    
    UIButton* backBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    [backBtn addTarget:self action:@selector(callPhone) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.tintColor=[UIColor whiteColor];
    [backBtn setImage:TKIMGetImage(@"kefu_phone") forState:UIControlStateNormal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
}
-(void)callPhone{
    NSMutableDictionary* dict=_user.userExt;
    NSString* phone;
    if (dict) {
        phone=dict[@"phone"];
    }
    
    if (!(phone&&phone.length)) {
        phone=@"95358";
    }
    
    if (phone&&phone.length) {
//        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    }else{
        [[TKIMLayerUtils instance] showTip:@"未获取到客服电话号码" hideAfterDelay:1];
    }
}
//返回按钮被点击
//_isNotify 则表示是策略商城 或客服
-(void)backClick:(UIButton*)btn{
    if(!_isNotify){
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if(_isNotify){
        if(nil == self.navigationController){
            NSLog(@"navigationController is nil");
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:TKIMSDK_BACK_CHAT_ACTION object:nil];
    }
}

-(UILabel*)reddot{
    if (_reddot==nil) {
        _reddot = [[UILabel alloc] init];
        _reddot.backgroundColor = [UIColor redColor];
        _reddot.layer.masksToBounds = YES;
        _reddot.layer.cornerRadius =5;
    }
    return _reddot;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    /*
    UIButton* titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 100, 30)];
    titleBtn.backgroundColor = [UIColor clearColor];
    [titleBtn setTintColor:[UIColor whiteColor]];
    [titleBtn setTitle:[TKIMHelper getShowNameWithUser:_user] forState:UIControlStateNormal];
    [titleBtn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //    self.navigationItem.title = [TKIMHelper getShowNameWithUser:_user];
    self.navigationItem.titleView = titleBtn;
     */
    
    
    
    self.navigationItem.title = [TKIMHelper getShowNameWithUser:_user];
    
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
//    manager.shouldResignOnTouchOutside = YES;
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = YES;
    
}


//标题栏被点击
-(void)titleClick:(UIButton*)btn{
    //    TKUserInfoViewController *ctl = [[TKUserInfoViewController alloc] init];
    //    ctl.fromContact = NO;
    //    _user.active = YES;
    //    ctl.user = _user;
    //    [ctl setHidesBottomBarWhenPushed:YES];
    //    [self.navigationController pushViewController:ctl animated:YES];
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    //请求公众号菜单
    [self loadOfficailMenu];
    //修改昵称的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modifyNickname) name:TKIMModifyNicknameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modifyUnreadNumber)
                                                 name:UIApplicationWillResignActiveNotification object:nil];
    
    //#warning 防止重复监听
    [[TKIMManager shareInstance] unRegisterDelegate:self];
    //#warning 注册代理监听
    [[TKIMManager shareInstance] registerDelegate:self];
//    self.automaticallyAdjustsScrollViewInsets=false;
    
    //    id data=[[TKIMInterfaceHelper sharedInstance] valueForKeyData:TKIMSDK_KEFU_USER_DATA];
    if (_isKeFu) {
        NSDictionary* dict=[TKIMCacheHelper valueForKey:SDK_CommonAllocation];
        NSInteger  step=[dict[@"prompt_cycle_time"] integerValue];
        NSString * key = [NSString stringWithFormat:@"%@-%@",[TKIMSDKManager getLoginUserPuid],kLASTSENDINITMSG_TIME];
        double oldTime=[TKIMCacheHelper doubleForKey:key];
        if (step == 0) {
            step = 60 ;
        }
        double time=[[NSDate date] timeIntervalSince1970];
        if ((time-oldTime)>step*60) {
            //初始化消息-客服第一次消息需要做这个处理
            TKIMMessage* msg=[self keFuinitMsg];
            msg.toUser = _user.userID;
            msg.toJid = _user.jid;
            msg.chatUserType = _user.userType;
            _msgInit = msg;
            [[TKIMManager shareInstance] sendMessage:msg];
        }
    }
}

-(void)modifyUnreadNumber{
    [[TKIMManager shareInstance] resetUserConverseCount:_user.userID];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //清除用户的会话数
    [[TKIMManager shareInstance] resetUserConverseCount:_user.userID];
    
    
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
//    manager.shouldResignOnTouchOutside = YES;
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = YES;
    
}


-(void) strangerFriend{
    NSString*  serviceCode = [_user.userExt objectForKey:@"service_code"];
    if(serviceCode != nil){
        NSString* crmid = (NSString *)[TKIMCacheHelper valueForKey:SDK_LOGINUSER_PUID];
        NSMutableString* friendKey = [NSMutableString stringWithFormat:@"5000007_%@_%@",crmid,serviceCode];
        NSString* isFriend = (NSString *)[TKIMCacheHelper valueForKey:friendKey];
        if(isFriend == nil)
        {
            dispatch_async(dispatch_get_global_queue(0,0), ^{
                //add strange friend
                [TKIMSDKManager addFriend:serviceCode cust_code:crmid callBack:^(TKIMResultVo *resultVo) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(resultVo.errorNo == 0){
                            NSLog(@"%@",@"5000007 add friend success");
                            //cache it
                            [TKIMCacheHelper setValue:@"1"  forKey:friendKey];
                        }else{
                            NSLog(@"%@",@"5000007 add friend failed");
                        }
                    });
                }];
            });
        }
    }
}

#pragma mark 方法
/**
 *  @Author lpm, 15-07-28 10:07:57
 *
 *  @brief  发送消息
 *
 *  @param msg 消息
 */
-(void)sendMessage:(TKIMMessage *)msg
{
    //add by yujinshi
    if(_isNotify){
        [self strangerFriend];
    }
    
    msg.toUser = _user.userID;
    msg.toJid = _user.jid;
    msg.chatUserType = _user.userType;
    
    if (_isKeFu) {
        msg= [self keFuSendMsgExt:msg];
    }else{
        msg.ext[@"intercept"] = @"0";
        //add by yujinshi
        NSString* appkey=[TKHttpService app_key];
        if (appkey&&appkey.length) {
            [msg.ext setObject:appkey forKey:@"app_key"];
        }
        NSString* app_type=[TKHttpService app_type];
        if (app_type&&app_type.length) {
            [msg.ext setObject:app_type forKey:@"app_type"];
        }
    }
    msg.isUpdateSenderInfo = NO;
    
    [[TKIMManager shareInstance] sendMessage:msg];
}


-(TKIMMessage*)keFuinitMsg{
    TKIMMessage* msg = [[TKIMMessage alloc] init];
    NSString* puid=[TKIMSDKManager getTouristAccountPuid];
    if (puid&&puid.length>0) {
        [msg.ext setObject:puid forKey:@"puid"];
    }
    [msg.ext setObject:@"customer" forKey:@"source"];
    [msg.ext setObject:@"1102000" forKey:@"funcNo"];
    NSString* appkey=[TKHttpService app_key];
    if (appkey&&appkey.length) {
        [msg.ext setObject:appkey forKey:@"app_key"];
    }
    NSString* app_type=[TKHttpService app_type];
    if (app_type&&app_type.length) {
        [msg.ext setObject:app_type forKey:@"app_type"];
    }
    [msg.ext setObject:@"window_init" forKey:@"type"];
    [msg.ext setObject:@"single_window" forKey:@"interactType"];
    [msg.ext setObject:@"" forKey:@"to_target_user"];
    [msg.ext setObject:@"normal" forKey:@"messageType"];
    [msg.ext setObject:@"kefu" forKey:@"channel"];
    [msg.ext setObject:@"app" forKey:@"onlinecs_channel_type"];
    msg.channel=1;
    msg.type = TKIMMsgTypeCmd;
    return msg;
}
-(TKIMMessage*)keFuSendMsgExt:(TKIMMessage*)msg{
    
    if (msg==nil) {
        return nil;
    }
    NSString* puid=[TKIMSDKManager getTouristAccountPuid];
    if (puid&&puid.length>0) {
        [msg.ext setObject:puid forKey:@"puid"];
    }
    [msg.ext setObject:@"customer" forKey:@"source"];
    [msg.ext setObject:@"1102000" forKey:@"funcNo"];
    NSString* appkey=[TKHttpService app_key];
    if (appkey&&appkey.length) {
        [msg.ext setObject:appkey forKey:@"app_key"];
    }
    NSString* app_type=[TKHttpService app_type];
    if (app_type&&app_type.length) {
        [msg.ext setObject:app_type forKey:@"app_type"];
    }
    [msg.ext setObject:@"" forKey:@"type"];
    [msg.ext setObject:@"single_window" forKey:@"interactType"];
    msg.channel=1;
    
    NSDictionary* data=(NSDictionary*)[[TKIMInterfaceHelper sharedInstance] valueForKeyData:TKIMSDK_KEFU_USER_DATA];
    
    NSString*to_target_user=@"";
    
    if (data) {
        to_target_user=[data valueForKey:@"toPuid"];
    }
    
    [msg.ext setObject:to_target_user forKey:@"to_target_user"];
    [msg.ext setObject:@"kefu" forKey:@"channel"];
    [msg.ext setObject:@"app" forKey:@"onlinecs_channel_type"];
    return msg;
}


/**
 *  @Author zrs, 15-12-11 09:12:11
 *
 *  @brief  查询历史消息委托
 *
 *  @param messageCount 消息数
 *  @param historyDataBlock 回调
 */
-(void)requestMoreHistoryMessagecount:(NSInteger)messageCount historyDataBlock:(void (^)(NSMutableArray *))historyDataBlock
{
    TKIMWS(weakself);
    TKIMMessage *msg = self.msgArray.firstObject;
    NSInteger startIndex = 1;
    if (msg) {
        startIndex = msg.refId.integerValue;
    }else{
        startIndex=-1;
    }
    [[TKIMManager shareInstance ] loadUserHisMsgFromServer:self.user.userID startIndex:startIndex count:messageCount :^(TKIMResultVo *resultVo) {
        if (resultVo.errorNo == 0) {
            NSMutableArray *array = (NSMutableArray *)resultVo.results;
            NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[array count])];
            [weakself.msgArray insertObjects:array atIndexes:indexes];
        }
        historyDataBlock([weakself.msgArray mutableCopy]);
    }];
}


/**
 *  @Author lpm, 16-05-10 09:05:46
 *
 *  @brief  请求公众号菜单
 */
-(void)loadOfficailMenu
{
    //请求公众号的菜单数据
    if (_user.userType == TKIMUserTypeOfficial)
    {
        TKIMRequestService * service =  [[TKIMRequestService alloc] init];
        [service getOfficialMenusWithUsername:_user.userID callBack:^(TKIMResultVo *resultVo) {
            if (resultVo.errorNo == 0) {
                self.chatView.menusArray = (NSArray *)resultVo.results;
            }else{
                [[TKIMLayerUtils instance] showTip:resultVo.errorInfo];
            }
        }];
    }
}


/**
 *  @author zhengrs, 16-04-29 11:04:35
 *
 *  @brief 修改昵称成功后重新刷新界面
 */
-(void)modifyNickname
{
    self.navigationItem.title = [TKIMHelper getShowNameWithUser:self.user];
    [[TKIMManager shareInstance] asyncQueryUserHisMessageByUserId:_user.userID callBack:^(NSMutableArray *array)
     {
         [_chatView reloadList:array isNeedTime:!self.user.isNeedMangerBtn];
     }];
}




#pragma mark 事件路由
/**
 *  @Author lpm, 15-12-02 13:12:11
 *
 *  @brief  事件路由
 *
 *  @param eventName
 *  @param userInfo
 */
-(void)routerEventWithName:(NSString *)eventName userInfo:(NSObject *)userInfo
{
    if ([eventName isEqualToString:TKIMSrvTemplOnclick]){
        [self jumpToOfficailDetail:userInfo];
    }
    else if ([eventName isEqualToString:TKIMSubMenuClickEvent]){
        [self officailMenuClickEvent:userInfo];
    }
    else if([eventName isEqualToString:TKIMAudioChatSelectedEvent]){
        [self jumpToVoiceChat:userInfo];
    }
    else if([eventName isEqualToString:TKIMVideoChatSelectedEvent]){
        [self jumpToVideoChat:userInfo];
    }
    else if ([eventName isEqualToString:TKIMLocationClickEvent]){
        [self jumpToMap:userInfo];
    }
    else if ([eventName isEqualToString:TKIMMsgHeadImageTapEvent]){
        [self msgHeadOnclick:userInfo];
    }
    else if([eventName isEqualToString:TKIMScoreEvent]){
        [self scoreEvent:userInfo];
    }
    else if([eventName isEqualToString:TKIMToScoreEvent]){
        NSLog(@"TKIMToScoreEvent===");
    }
    else if([eventName isEqualToString:TKIMLinkOnClick]){
        [self linkOnClick:userInfo];
    }else if([eventName isEqualToString:@"Delete_Msg"]){
        
        //        [self doStateChange:1];
    }
}


/**
 *  @Author lpm, 16-05-10 10:05:27
 *
 *  @brief  跳转到公众号详情
 *
 *  @param userInfo
 */
-(void)jumpToOfficailDetail:(NSObject *)userInfo
{
    TKIMSrvRichItem* item = (TKIMSrvRichItem *)userInfo;
    if (item&&item.url&&item.url.length>0) {
        
        /*
        TKIMOfficalDetailViewController *detail = [[TKIMOfficalDetailViewController alloc] init];
        detail.item = item;
        detail.isAutoTitle=NO;
        detail.navtitle=self.navigationItem.title;
        [self.navigationController pushViewController:detail animated:YES];
         */
        
        //  没删除TKIMOfficalDetailViewController，只是工程下删除了引用
        
        EBMWebViewViewController *webView = [[EBMWebViewViewController alloc]initWithUrlString:item.url titleString:self.navigationItem.title];
        [self.navigationController pushViewController:webView animated:YES];
    }
}


/**
 *  @Author lpm, 16-05-10 10:05:36
 *
 *  @brief  公众号子菜单点击
 *
 *  @param userInfo
 */
-(void)officailMenuClickEvent:(NSObject *)userInfo
{
    
    /*
    TKIMOfficalDetailViewController *detail = [[TKIMOfficalDetailViewController alloc] init];
    detail.menuItem = (TKIMMenuBarItem *)userInfo;
    [self.navigationController pushViewController:detail animated:YES];
     */

    TKIMMenuBarItem * menuItem = (TKIMMenuBarItem *)userInfo;
    
    EBMWebViewViewController *webView = [[EBMWebViewViewController alloc]initWithUrlString:menuItem.key titleString:menuItem.menu_name];
    [self.navigationController pushViewController:webView animated:YES];
    
}


/**
 *  @Author lpm, 16-05-10 10:05:27
 *
 *  @brief  语音聊天
 *
 *  @param userInfo
 */
-(void)jumpToVoiceChat:(NSObject *)userInfo
{
    [[TKIMLayerUtils  instance] showLoading:YES withLabel:@"连接中"];
    [[TKIMManager shareInstance] sendVoiceRequestTo:_user.userID];
}


/**
 *  @Author lpm, 16-05-10 10:05:33
 *
 *  @brief  视频聊天
 *
 *  @param userInfo
 */
-(void)jumpToVideoChat:(NSObject *)userInfo
{
    [[TKIMLayerUtils  instance] showLoading:YES withLabel:@"连接中"];
    [[TKIMManager shareInstance] sendVideoRequestTo:_user.userID];
}


/**
 *  @Author lpm, 16-05-10 10:05:17
 *
 *  @brief  跳转到地图
 *
 *  @param userInfo
 */
-(void)jumpToMap:(NSObject *)userInfo
{
    TKIMLocationViewController *location = [[TKIMLocationViewController alloc] init];
    if(userInfo)
    {
        location.location = (TKIMLocationMessage *)userInfo;
    }
    location.delegate = _chatView;
    [self.navigationController pushViewController:location animated:YES];
}


/**
 *  @Author lpm, 16-05-10 10:05:11
 *
 *  @brief  消息头像点击事件
 *
 *  @param userInfo
 */
-(void)msgHeadOnclick:(NSObject *)userInfo
{
    
    return;
    
    //    TKIMMessage * message = (TKIMMessage*)userInfo;
    //    NSString * userID = message.fromUser;
    //    if ([[TKIMSDKHelper getLoginUserName] isEqualToString:userID]) {//自己
    //        TKIMAccountDeatilViewController * detailVC = [[TKIMAccountDeatilViewController alloc] init];
    //        [self.navigationController pushViewController:detailVC animated:YES];
    //    }else{//好友
    //        [self jumpToFriendInformation];
    //    }
}


/**
 *  @Author lpm, 16-05-10 10:05:43
 *
 *  @brief 打分
 *
 *  @param userInfo
 */
-(void)scoreEvent:(NSObject *)userInfo
{
    [[TKIMLayerUtils instance] showLoading:YES];
    [[TKIMManager shareInstance] sendScoreRequest:_user.userID callBack:^(TKIMResultVo *resultVo) {
        [[TKIMLayerUtils instance] showLoading:NO];
        [[TKIMLayerUtils instance] showTip:resultVo.errorInfo];
        NSLog(@"%@",resultVo.errorInfo);
    }];
}


/**
 *  @Author lpm, 16-05-10 11:05:06
 *
 *  @brief  链接被点击
 *
 *  @param userInfo
 */
-(void)linkOnClick:(NSObject *)userInfo
{
    /*
    TKIMOfficalDetailViewController *detail = [[TKIMOfficalDetailViewController alloc] init];
    TKIMSrvRichItem *item = [[TKIMSrvRichItem alloc] init];
    item.url = (NSString *)userInfo;
    item.title = [TKIMHelper getShowNameWithUser:_user];
    detail.item = item;
    [self.navigationController pushViewController:detail animated:YES];
    */
    
    
    TKIMMenuBarItem * menuItem = (TKIMMenuBarItem *)userInfo;
    
    EBMWebViewViewController *webView = [[EBMWebViewViewController alloc]initWithUrlString:(NSString *)userInfo titleString:[TKIMHelper getShowNameWithUser:_user]];
    [self.navigationController pushViewController:webView animated:YES];
    
}

#pragma mark 监听代理（更多代理可在TKIMManagerDelegate中查看）

//#warning 特别注意以下为im代理监听，必须注册为监听代理才会被调用
/**
 *  @Author lpm, 15-09-16 13:09:17
 *
 *  @brief  收到消息
 *
 *  @param sender
 *  @param message
 */
-(void)didReceiveServerStatus:(TKIMStatus *)status{
    
    if (status.statusCode == TKIMLoginSuccess) {
        
    }
    
}
- (void)didReceiveMessage:(TKIMMessage *)message
{
    if( message)
    {
        
        if ([message.fromUser isEqualToString:_user.userID])
        {
            
            
            if ((message.chatUserType!=TKIMUserTypeGroup)&&(message.chatUserType!=TKIMUserTypeRoom)) {
                [_chatView receiveMsg:message];
            }
            
        }else{
            [self backStyle];
        }
    }
}


/**
 *  @Author lpm, 15-11-07 12:11:27
 *
 *  @brief  消息发送结果回调
 *
 *  @param message
 *  @param error
 */
-(void)didSendMessage:(TKIMMessage *)message error:(NSError *)error
{
    if (_msgInit&&[_msgInit.messageId  isEqualToString:message.messageId]) {
        
        double time=[[NSDate date] timeIntervalSince1970];
        NSString * key = [NSString stringWithFormat:@"%@-%@",[TKIMSDKManager getLoginUserPuid],kLASTSENDINITMSG_TIME];
        
        [TKIMCacheHelper setDouble:time forKey:key];
        
    }
    
    [_chatView updateMsg:message];
}

/**
 *  @Author lpm, 15-12-09 15:12:59
 *
 *  @brief  收到消息被清空事件
 *
 *  @param error
 */
-(void)didReceiveMessageClean:(NSError *)error;
{
    [_chatView reloadList:[@[] mutableCopy] isNeedTime:!self.user.isNeedMangerBtn];
}

/**
 *  @Author lpm, 15-12-17 10:12:41
 *
 *  @brief  收到app被杀死或者退出登录的事件
 */
-(void)didReceiveAppInterruption
{
    //清除用户的会话数
    [[TKIMManager shareInstance] resetUserConverseCount:_user.userID];
}

/**
 *  @Author lpm, 15-12-02 19:12:09
 *
 *  @brief
 *
 *  @param data
 *  @param error
 */
-(void)didReceiveVideoVoiceChatRequestResult:(TKIMVideoChat *)data error:(NSError *)error
{
    [[TKIMLayerUtils  instance] showLoading:NO];
    if (!error)
    {
        data.userName = _user.userID;
        [[NSNotificationCenter defaultCenter] postNotificationName:TKIMShowVideoVoiceNotification object:data];
    }
    else
    {
        NSDictionary *userInfo = error.userInfo;
        NSString *tip = userInfo[@"errorInfo"];
        [[TKIMLayerUtils instance] showTip:tip];
    }
}


#pragma mark 属性
-(NSMutableArray *)menusArray
{
    if (!_menusArray)
    {
        _menusArray = [NSMutableArray array];
    }
    return _menusArray;
}


-(void)dealloc
{
//    [_chatView removeCss];
    _chatView = nil;
    //    _timer=nil;
    //#warning 解注代理监听
    [[TKIMManager shareInstance] unRegisterDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
